package com.acheli.registry.network.packet;

import com.acheli.ACHeli;
import com.acheli.registry.network.ACHMessages;
import com.acheli.registry.network.ACHeliPacketType;
import com.acheli.registry.network.ICustomSyncable;
import com.acheli.rideable.entites.ComponentEntity;
import com.acheli.rideable.entites.RideableEntity;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.simple.SimpleChannel;

import java.util.UUID;
import java.util.function.Supplier;

public class CustomSyncableS2CPacket {
    // 添加字符串字段
    private final CompoundTag tag;

    // 从字节缓冲区解码
    public CustomSyncableS2CPacket(FriendlyByteBuf buf) {
        this.tag = buf.readNbt();
    }

    public CustomSyncableS2CPacket(int senderId, CompoundTag data, ACHeliPacketType packetType) {
        tag = data;
        tag.putInt("senderId", senderId);
        tag.putString("packetType", packetType.name());
    }

    // 编码到字节缓冲区
    public void toBytes(FriendlyByteBuf buf) {
        buf.writeNbt(tag);
    }

    private boolean handle(Supplier<NetworkEvent.Context> supplier) {
        int senderId = tag.getInt("senderId");
        NetworkEvent.Context context = supplier.get();
        context.enqueueWork(() -> {
            LocalPlayer localPlayer = Minecraft.getInstance().player;
            if (localPlayer != null) {
                ClientLevel level = localPlayer.clientLevel;
                if  (level.getEntity(senderId) instanceof ICustomSyncable syncable
                ) {
                    ACHeliPacketType packetType = ACHeliPacketType.valueOf(tag.getString("packetType"));
                    syncable.clientReceive(tag,tag.getInt("originId")==senderId, packetType);
                }

            }
        });
        return true;
    }

    public static void register(SimpleChannel channel) {
        channel.messageBuilder(CustomSyncableS2CPacket.class, ACHMessages.id(), NetworkDirection.PLAY_TO_CLIENT)
                .decoder(CustomSyncableS2CPacket::new)
                .encoder(CustomSyncableS2CPacket::toBytes)
                .consumerMainThread(CustomSyncableS2CPacket::handle)
                .add();
    }
}